<script lang="ts" setup>
import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import {
  Button,
  Collapse,
  CollapsePanel,
  Dropdown,
  Menu,
  MenuItem,
  message,
  Select,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

import {
  getAttachmentRelationList,
  getGoodsPurchaseList,
  setFileData,
} from '#/api/goodsPurchase';
import { getPurchaseList } from '#/api/purchase';
import { supplylList } from '#/api/supply';
import { getProcessPurchaseList } from '#/api/backend/processPurchase';

import fileLists from './fileList.vue';
import UpdataFile from './upload-dragger.vue';
import {factorylList} from "#/api/factory";

type EmitEvents = {
  close: [];
};
const emit = defineEmits<EmitEvents>();
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  confirmText: '保存',
  class: 'w-4/6',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    modalApi.lock(true);
    if (info.type === '2') {
      const parmas = {
        file_data: info.data,
        relationId: info.relationId[0],
        scene: 'scm_goods_purchase',
      };
      setFileData(parmas).then((res: any) => {
        modalApi.unlock();
        if (res.data.code === 1) {
          message.success(res.data.msg);
          modalApi.close();
          emit('close');
        } else {
          message.error(res.data.msg);
        }
      });
    } else if (info.type === '1') {
      const parmas = {
        file_data: info.data,
        relationId: info.relationId[0],
        scene: 'scm_purchase',
      };
      setFileData(parmas).then((res: any) => {
        modalApi.unlock();
        if (res.data.code === 1) {
          message.success(res.data.msg);
          modalApi.close();
          emit('close');
        } else {
          message.error(res.data.msg);
        }
      });
    } else if (info.type === '3' || info.type === '4') {
      // 供应商保存
      const parmas = {
        file_data: info.data,
        relationId: info.relationId[0],
        scene: 'scm_supply',
      };
      setFileData(parmas).then((res: any) => {
        modalApi.unlock();
        if (res.data.code === 1) {
          message.success(res.data.msg);
          modalApi.close();
          emit('close');
        } else {
          message.error(res.data.msg);
        }
      });
    } else if (info.type === '5') {
      // 工序采购保存
      const parmas = {
        file_data: info.data,
        relationId: info.relationId[0],
        scene: 'scm_process_purchase',
      };
      setFileData(parmas).then((res: any) => {
        modalApi.unlock();
        if (res.data.code === 1) {
          message.success(res.data.msg);
          modalApi.close();
          emit('close');
        } else {
          message.error(res.data.msg);
        }
      });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return;
    const { data, type, search } = modalApi.getData<Record<string, any>>()
    info.type = type;
    info.relationId = data;
    info.search = search

    console.log(search)
    if (type == '1') {
      if (data.length === 1) {
        getAttachmentRelationList({
          relationId: data[0],
          scene: 'scm_purchase',
        }).then((res: any) => {
          info.data = res.data.data;
        });
      }
      getPurchaseListFile()
    } else if (type === '2') {
      // 启动大货采购单相关配置
      // 请求单独行数据
      if (data.length === 1) {
        getAttachmentRelationList({
          relationId: data[0],
          scene: 'scm_goods_purchase',
        }).then((res: any) => {
          info.data = res.data.data;
        });
      }
      getGoodsPurchaseListFile();
    } else if (type === '3') {
      // 启动供应商
      // 请求单独行数据
      if (data.length === 1) {
        getAttachmentRelationList({
          relationId: data[0],
          scene: 'scm_supply',
        }).then((res: any) => {
          info.data = res.data.data;
        });
      }
      getSupplyListFile();
    } else if (type === '4') {
      // 启动货品供应商
      // 请求单独行数据
      if (data.length === 1) {
        getAttachmentRelationList({
          relationId: data[0],
          scene: 'scm_supply',
        }).then((res: any) => {
          info.data = res.data.data;
        });
      }
      getFactoryListFile();
    } else if (type === '5') {
      // 启动工序采购
      // 请求单独行数据
      if (data.length === 1) {
        getAttachmentRelationList({
          relationId: data[0],
          scene: 'scm_process_purchase',
        }).then((res: any) => {
          info.data = res.data.data;
        });
      }
      getProcessPurchaseListFile();
    }
  },
});

const activeKey = ref(['1', '2']);
// 处理菜单点击事件，获取选中的菜单项值
const menuCongfig = ref([
  {
    count: '',
    value: '营业执照',
    label: '营业执照',
  },
  {
    count: '',
    value: '签订合同',
    label: '签订合同',
  },
  {
    value: '财务',
    label: '财务',
    count: '',
  },
  {
    value: '资质',
    label: '资质',
    count: '',
  },
  {
    value: '其他',
    label: '其他',
    count: '',
  },
]);
const info = reactive({
  relationId: [],
  type: '', // 1 物料采购  2 大货采购单  3 供应商  4 货品供应商  5 工序采购
  path: '', // 文件路径
  data: [] as any,
  search:''
});
const handleMenuClick = (e: any) => {
  const selectedValue = e.key; // 获取选中的菜单项值
  // 大货采购单
  switch (info.type) {
    case '1': {
      getPurchaseListFile(selectedValue);
      break;
    }
    case '2': {
      getGoodsPurchaseListFile(selectedValue);
      break;
    }
    case '3': {
      getSupplyListFile(selectedValue);
      break;
    }
    case '4': {
      getFactoryListFile(selectedValue);
      break;
    }
    case '5': {
      getProcessPurchaseListFile(selectedValue);
      break;
    }
    // No default
  }
};

// 获取大货采购单文件情况
function getGoodsPurchaseListFile(selectedValue?: string) {
  info.path = '';
  // 模式 有传selectedValue 就是根据条件查询 否则就是查询所有，查询所有不会返回文件路径
  const parmas = {
    exportFilesScene: selectedValue, // 类型
    tableSize: 'small',
    order: 'purchase_date,desc',
    exportFilesType: selectedValue ? 1 : 2,
    search:info.search,
  };

  getGoodsPurchaseList(parmas).then((res: any) => {
    // 有传selectedValue 就是根据条件查询 否则就是查询所有，查询所有不会返回文件路径
    if (selectedValue) {
      if (res.code !== 0) {
        info.path = res;
      }
    } else {
      if (res && res.length > 0) {
        // 清空现有count值
        menuCongfig.value.forEach((item) => {
          item.count = '';
        });
        // 更新匹配项的count值
        res.forEach((item: any) => {
          // 查找匹配的菜单项并更新count
          const menuItem = menuCongfig.value.find(
            (menu) => menu.value === item.title,
          );
          if (menuItem) {
            menuItem.count = item.count;
          }
        });
      }
    }
  });
}

// 获取物料采购文件情况

function getPurchaseListFile(selectedValue?: string) {
  info.path = '';
  // 模式 有传selectedValue 就是根据条件查询 否则就是查询所有，查询所有不会返回文件路径
  const parmas = {
    exportFilesScene: selectedValue, // 类型
    order: 'purchase_id,desc',
    exportFilesType: selectedValue ? 1 : 2,
    search:info.search,
  };

  getPurchaseList(parmas).then((res: any) => {
    // 有传selectedValue 就是根据条件查询 否则就是查询所有，查询所有不会返回文件路径
    if (selectedValue) {
      if (res.code !== 0) {
        info.path = res;
      }
    } else {
      if (res && res.length > 0) {
        // 清空现有count值
        menuCongfig.value.forEach((item) => {
          item.count = '';
        });
        // 更新匹配项的count值
        res.forEach((item: any) => {
          // 查找匹配的菜单项并更新count
          const menuItem = menuCongfig.value.find(
            (menu) => menu.value === item.title,
          );
          if (menuItem) {
            menuItem.count = item.count;
          }
        });
      }
    }
  });
}

// 获取供应商文件情况
function getSupplyListFile(selectedValue?: string) {
  const parmas = {
    Supplytype: 1,
    exportFilesType: selectedValue ? 1 : 2,
    exportFilesScene: selectedValue,
    search:info.search,
  };
  supplylList(parmas).then((res: any) => {
    if (selectedValue) {
      if (res.code !== 0) {
        info.path = res;
      }
    } else {
      if (res && res.length > 0) {
        // 清空现有count值
        menuCongfig.value.forEach((item) => {
          item.count = '';
        });
        // 更新匹配项的count值
        res.forEach((item: any) => {
          // 查找匹配的菜单项并更新count
          const menuItem = menuCongfig.value.find(
            (menu) => menu.value === item.title,
          );
          if (menuItem) {
            menuItem.count = item.count;
          }
        });
      }
    }
  });
}


// 获取货品供应商文件情况
function getFactoryListFile(selectedValue?: string) {
  const parmas = {
    exportFilesType: selectedValue ? 1 : 2,
    exportFilesScene: selectedValue,
    search:info.search,
  };
  factorylList(parmas).then((res: any) => {
    if (selectedValue) {
      if (res.code !== 0) {
        info.path = res;
      }
    } else {
      if (res && res.length > 0) {
        // 清空现有count值
        menuCongfig.value.forEach((item) => {
          item.count = '';
        });
        // 更新匹配项的count值
        res.forEach((item: any) => {
          // 查找匹配的菜单项并更新count
          const menuItem = menuCongfig.value.find(
            (menu) => menu.value === item.title,
          );
          if (menuItem) {
            menuItem.count = item.count;
          }
        });
      }
    }
  });
}

// 获取工序采购文件情况
function getProcessPurchaseListFile(selectedValue?: string) {
  info.path = '';
  // 模式 有传selectedValue 就是根据条件查询 否则就是查询所有，查询所有不会返回文件路径
  const parmas = {
    exportFilesScene: selectedValue, // 类型
    order: 'id,desc',
    exportFilesType: selectedValue ? 1 : 2,
    search:info.search,
  };

  getProcessPurchaseList(parmas).then((res: any) => {
    // 有传selectedValue 就是根据条件查询 否则就是查询所有，查询所有不会返回文件路径
    if (selectedValue) {
      if (res.code !== 0) {
        info.path = res;
      }
    } else {
      if (res && res.length > 0) {
        // 清空现有count值
        menuCongfig.value.forEach((item) => {
          item.count = '';
        });
        // 更新匹配项的count值
        res.forEach((item: any) => {
          // 查找匹配的菜单项并更新count
          const menuItem = menuCongfig.value.find(
            (menu) => menu.value === item.title,
          );
          if (menuItem) {
            menuItem.count = item.count;
          }
        });
      }
    }
  });
}

// 点击下载
function handleDowloadClick() {
  window.open(info.path);
}

const columns: any = [
  { dataIndex: 'title', title: '附件类型', align: 'center' },
  { dataIndex: 'urls', title: '附件', align: 'center' },
  { dataIndex: 'action', title: '操作', width: 110, align: 'center' },
];

// 添加行
function add() {
  info.data.push({ title: '', urls: [], fileList: [] });
}
function del(index: number) {
  info.data.splice(index, 1);
}
const tableIndex: any = ref();
function handleFilePushData(data: any) {
  const index = tableIndex.value;
  const urls = data.map((item: any) => item.url);
  info.data[index].urls = [...info.data[index].urls, ...urls];
}

function selectFile(index: number) {
  tableIndex.value = index;
  fileListModalApi.setData({}).open();
}

function openFile(url: string) {
  const modifiedPath = url
  window.open(`https://yyq.babiboy.com/${modifiedPath}`);
}

function handleRemoveFile(record: any, index: number) {
  record.urls.splice(index, 1);
  message.success('文件已删除');
}

function handleUploadSuccess(record: any, url: any) {
  // 初始化urls数组（如果不存在）
  if (!record.urls) {
    record.urls = [];
  }
 record.urls =url.map((item: any) => item.response.key);

  message.success('上传成功');
}
const [fileListModal, fileListModalApi] = useVbenModal({
  connectedComponent: fileLists,
});
</script>

<template>
  <Modal title="附件管理">
    <Collapse v-model:active-key="activeKey" :bordered="false">
      <CollapsePanel key="1" header="导出外面筛选结果下-所有相关附件">
        <Space>
          <Dropdown>
            <Button type="primary">导出附件</Button>
            <template #overlay>
              <Menu @click="handleMenuClick">
                <template v-for="value in menuCongfig" :key="value.value">
                  <MenuItem>
                    {{
                      `${value.value}${value.count ? ` (${value.count})` : ''}`
                    }}
                  </MenuItem>
                </template>
              </Menu>
            </template>
          </Dropdown>
          <template v-if="info.path != ''">
            <Button type="primary" @click="handleDowloadClick">点击下载</Button>
          </template>
        </Space>
      </CollapsePanel>
      <CollapsePanel key="2" header="附件上传">
        <Button
          type="primary"
          class="caret-green-500"
          v-if="info.relationId.length == 1"
          @click="add()"
        >
          添加附件行
        </Button>
      </CollapsePanel>
      <Table :columns="columns" :data-source="info.data">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'title'">
            <Select
              v-model:value="record.title"
              show-search
              allow-clear
              placeholder="请输入供应商关键词"
              :filter-option="false"
              :options="menuCongfig"
              style="width: 100%"
            />
          </template>
          <template v-else-if="column.dataIndex === 'urls'">
            <div>
              <Space>
                <div>
                  <UpdataFile
                    v-model:file-list="record.fileList"
                    :multiple="true"
                    @upload-success="(url) => handleUploadSuccess(record, url)"
                  />
                </div>
                <Button type="primary" @click="selectFile(index)">
                  选择文件
                </Button>
              </Space>
            </div>
            <div v-for="(item, idx) in record.urls" :key="item">
              <Tag
                class="mt-1"
                @click="openFile(item)"
                closable
                @close="handleRemoveFile(record, idx)"
              >
                {{ item.split('/').pop() }}
              </Tag>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <Button type="primary" danger @click="del(index)">删除</Button>
          </template>
        </template>
      </Table>
    </Collapse>
    <fileListModal @push-data="handleFilePushData" />
  </Modal>
</template>

<style scoped>
/* 让 Form.Item 不再有默认 margin-bottom */
.mb-0 {
  margin-bottom: 0 !important;
}
</style>
